"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _find = _interopRequireDefault(require("./find"));
/**
 * 树节点交换顺序，会改变原始数据
 * @param treeNodes
 * @param options
 * @returns
 */
const exchange = (treeNodes, targetNode, sourceNode, options) => {
  const {
    uniqueKey = 'key',
    childrenKey = 'children'
  } = options ?? {};
  const realTargetNode = (0, _find.default)(treeNodes, node => node[uniqueKey] === targetNode[uniqueKey], {
    childrenKey
  });
  const realSourceNode = (0, _find.default)(treeNodes, node => node[uniqueKey] === sourceNode[uniqueKey], {
    childrenKey
  });
  if (!realTargetNode) {
    throw new Error('targetNode is not existed');
  }
  if (!realSourceNode) {
    throw new Error('source is not existed');
  }
  if (targetNode[childrenKey]?.length && (0, _find.default)([targetNode], node => node[uniqueKey] === sourceNode[uniqueKey], {
    childrenKey
  })) {
    throw new Error("sourceNode cannot be in targetNode's children");
  }
  if (sourceNode[childrenKey]?.length && (0, _find.default)([sourceNode], node => node[uniqueKey] === targetNode[uniqueKey], {
    childrenKey
  })) {
    throw new Error("targetNode cannot be in sourceNode's children");
  }

  // 以免 children 等持有相同的引用
  const sourceNodeTemp = {
    ...sourceNode
  };
  const targetNodeTemp = {
    ...targetNode
  };
  Object.keys(sourceNodeTemp).map(key => {
    realTargetNode[key] = sourceNodeTemp[key];
  });
  Object.keys(targetNodeTemp).map(key => {
    realSourceNode[key] = targetNodeTemp[key];
  });

  // 目标节点的 children 已被复制给源节点，删除目标节点的 children
  if (childrenKey in targetNodeTemp && !(childrenKey in sourceNodeTemp)) {
    delete realTargetNode[childrenKey];
  }
  if (childrenKey in sourceNodeTemp && !(childrenKey in targetNodeTemp)) {
    delete realSourceNode[childrenKey];
  }
  return treeNodes;
};
var _default = exports.default = exchange;